package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.ResponseProcessorImp;

import java.util.Date;
import java.util.concurrent.BlockingQueue;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressValue;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ReadInputDiscretesRequest;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.procimg.DigitalIn;
import net.wimpi.modbus.procimg.SimpleDigitalIn;
import net.wimpi.modbus.util.BitVector;

public class ReadInputDiscretesResponseProcessor extends
		AbstractResponseProcessor {
	
	private static final Integer INT_1 = new Integer(1);
	private static final Integer INT_0 = new Integer(0);
	
	@Override
	public void processResponse(ModbusRequest req, ModbusResponse res, BlockingQueue<AddressValue> queue) {
		// TODO ReadInputDiscretesResponseProcessor errores IllegalAddressException
		if(res instanceof ReadInputDiscretesResponse && req instanceof ReadInputDiscretesRequest ){
			
			BitVector bits = ((ReadInputDiscretesResponse) res).getDiscretes();
			int baseDir = ((ReadInputDiscretesRequest)req).getReference();
			int bitCount = ((ReadInputDiscretesRequest)req).getBitCount();
			Date date = new Date();
			
			for(int i = 0; i < bitCount; i++){
				
				int address = baseDir + i;
				DigitalIn value = new SimpleDigitalIn(bits.getBit(i));

				AddressValue newValue = new AddressValue();
				newValue.setAddress(address);
				newValue.setAddressType(AddressType.DISCRETE);
				newValue.setDate(date);
				if(value.isSet())
				   newValue.setValue(INT_1);
				else
				   newValue.setValue(INT_0);
				
				queue.add(newValue);
				getImage().setDigitalIn(address,value,date);
				
				//TODO: Descomentar
				/*
				if( getDeciveDAO() != null )
					if(value.isSet())
						getDeciveDAO().saveValue( getDevice(), address ,INT_1 , AddressType.DISCRETE );
					else
						getDeciveDAO().saveValue( getDevice(), address ,INT_0 , AddressType.DISCRETE );
				*/	
			}
		}
	}

}
